package com.zhuangxiaoyan.springboot.jpa.infrastructure.config;

import com.zhuangxiaoyan.springboot.jpa.infrastructure.constant.ThreadPoolConstants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * ThreadPoolConfig 线程池配置类
 *
 * @author xjl
 * @version 2025/01/14 08:42
 **/
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Bean("asyncTaskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 使用常量配置参数
        executor.setCorePoolSize(ThreadPoolConstants.CORE_POOL_SIZE);
        executor.setMaxPoolSize(ThreadPoolConstants.MAX_POOL_SIZE);
        executor.setQueueCapacity(ThreadPoolConstants.QUEUE_CAPACITY);
        executor.setKeepAliveSeconds(ThreadPoolConstants.KEEP_ALIVE_SECONDS);
        executor.setThreadNamePrefix(ThreadPoolConstants.THREAD_NAME_PREFIX);
        // 拒绝策略：由调用线程处理
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池
        executor.initialize();
        return executor;
    }
}